package org.example.juc;

/**
 * @author 张琪
 * @date 2024/4/17 14:27
 */
public class ThreadLocalExample {

    public static void main(String[] args) {

    }

    public static void threadLocalTest() {
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        Thread thread = new Thread(() -> {
            threadLocal.set(1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(threadLocal.get());
            threadLocal.remove();
        });

        Thread thread2 = new Thread(() -> {
            threadLocal.set(2);
            threadLocal.remove();
        });

        thread.start();
        thread2.start();
    }

    public static void daemonTest() {
        Thread thread = new Thread(() -> System.out.println("hello world"));
        // 设置为守护线程,  当main方法(非守护方法)执行完成后, 会关闭所有的守护线程, 因此不会打印hello world
        thread.setDaemon(true);
        thread.start();
    }
}
